<%@ page import="com.deepai.dprsmgr.utils.ErrCode" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="sp" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@include file="../base_path.jsp" %>

<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="description" content="">

    <link rel="stylesheet" type="text/css" href="<%=basePath%>/lib/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen"
          href="<%=basePath%>/lib/jqgrid/5.2.1/css/ui.jqgrid-bootstrap.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/lib/lobibox/css/lobibox.min.css"/>
    <link type="text/css" rel="stylesheet" href="<%=basePath%>/lib/bootstrap-select/css/bootstrap-select.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/css/mycss.css"/>
    <style type="text/css">
        .header-right {
            position: absolute;
            right: 0px;
            top: 0px;
            bottom: inherit;
        }

        .col-xs-2 {
            width: 11%;
        }

        #form_filter .control-label {
            float: left;
        }
    </style>
    <title>人工通话</title>

</head>
<body>
<div class="navbar-fixed-top">
    <div class="breadcrumb">
        <span>业务中心</span>/

        <%--<span><a href="<%=basePath%>/task/showTaskManager.do">任务管理</a></span>/--%>
        <span class="active">人工通话</span>
        <span class="pull-right" title="刷新">
           <div class="btn-refresh" onclick="location.replace(location.href);">
           	<img src="<%=basePath%>/images/refresh.png">
           </div>
        </span>

    </div>
</div>

<div class="container-fluid" style="margin-top: 40px;">
    <div class="container-fluid-main">
        <div class="page-header">
            <h3>人工通话</h3>
        </div>
        <div class="panel-group" id="accordion">
            <div class="panel panel-default panel-default-sample">
                <div class="panel-body">
                    <form class="form-horizontal" role="form" id="form_filter">
                        <div class="form-group">
                            <label class="control-label" style="float: left; margin-left: 50px">接听时间</label>
                            <div class="col-xs-2">
                                <input type="text" class="form-control input-sm Wdate" id="begin_date"
                                       autocomplete="off"
                                       disableautocomplete placeholder="开始时间"
                                       onclick="var end_date=$dp.$('end_date');WdatePicker({isShowClear:false,
                                   onpicked:function(dq){var myobj=isCleanEndDate(dq.cal.getNewDateStr(),end_date.value);
                                   if(!myobj.ispass){end_date.value=myobj.maxDay;}},
                                       errDealMode:1,dateFmt: 'yyyy-MM-dd', maxDate:'%y-%M-%d'})">
                            </div>
                            <label class="control-label" style="padding-left: 0;">至</label>
                            <div class="col-xs-2">
                                <input type="text" class="form-control input-sm Wdate" id="end_date" autocomplete="off"
                                       disableautocomplete placeholder="结束时间"
                                       onclick="var begin_date=$dp.$('begin_date');var begin_datestr=begin_date.value;if(isEmpty(begin_datestr)){
                                        bootbox.alert('请先选择开始日期');return false;}
                                       WdatePicker({isShowClear:false,errDealMode:1,dateFmt: 'yyyy-MM-dd',
                                       minDate:'#F{$dp.$D(\'begin_date\')}', maxDate:'#F{getMaxDay($dp.$D(\'begin_date\'))}'})">
                            </div>

                            <label class="control-label" style="float: left; margin-left: 50px" for="txt_phone_number">来电号码</label>
                            <div class="col-xs-2">
                                <input type="text" class="form-control input-sm" id="txt_phone_number"
                                       name="txt_phone_number"
                                       maxlength="15" placeholder="请输入手机号">
                            </div>

                            <label class="control-label" style="float: left; margin-left: 50px" for="txt_phone_number">坐席分机</label>
                            <div class="col-xs-2">
                                <input type="text" class="form-control input-sm" id="destinationNumber"
                                       name="txt_phone_number"
                                       maxlength="15" placeholder="坐席分机">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label" style="float: left; margin-left: 50px">通话时长（秒）</label>
                            <div class="col-xs-4 form-inline" style="width: inherit;">
                                <input type="text" class="form-control col-xs-1 input-sm" id="txt_min_duration"
                                       name="txt_min_duration" placeholder="最小时长">
                                <label class="control-label col-xs-1">-</label>
                                <input type="text" class="form-control col-xs-1 input-sm" id="txt_max_duration"
                                       name="txt_max_duration" placeholder="最大时长">
                            </div>
                            <div class="col-xs-2">
                                <button class="btn btn-primary btn-sm" id="btn_query" type="button">查询</button>
                            </div>
                            <div class="col-xs-2" style="float: right">
                                <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"
                                        aria-haspopup="true" aria-expanded="false">
                                    <span class="glyphicon glyphicon-download-alt"></span>
                                    导出
                                    <span class="caret"></span>
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a href="javascript:void (0);" id="export_excel">数据列表</a></li>
                                    <li><a href="javascript:void (0);" id="export_audio">语音</a></li>

                                </ul>

                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>

        <table id="artificialJQGrid"></table>
        <div style="height: 40px" id="artificialJQGridPager"></div>
    </div>
</div>

<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:1200px;">
        <div class="modal-content" style="width:1200px;">

        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=basePath%>/lib/jquery/1.11.0/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap/3.3.7/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootbox/bootbox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/My97DatePicker/4.8/WdatePicker.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/lobibox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/messageboxes.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/notifications.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/bootstrap-select.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/wavesurfer.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/wavesurfer.regions.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>
<!--/_footer 作为公共模版分离出去-->

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript">
    var arr_dialog_info, call_info, curRowData;
    var waveSurfer;
    var lastCallId, nextCallId, call_id
    var $table = "#artificialJQGrid";
    var $formFilter = $("#form_filter");
    var $txtPhoneNumber = $("#txt_phone_number");
    var $txtMinDuration = $("#txt_min_duration");
    var $txtMaxDuration = $("#txt_max_duration");
    //输入规则判断
    $txtPhoneNumber.keyup(function () {
        var tmpTxt = $(this).val();
        $(this).val(tmpTxt.replace(/\D/g, ''));
    }).bind("paste", function () {
        var tmpTxt = $(this).val();
        $(this).val(tmpTxt.replace(/\D/g, ''));
    }).css("ime-mode", "disabled");
    var phone = "";
    $txtPhoneNumber.bind('input propertychange', function () {
        var curLikePhone = $(this).val().trim();
        if (curLikePhone === phone) {
            return;
        }
        phone = curLikePhone;
//            refreshJQGrid();
    });

    $txtMinDuration.keyup(function () {
        var tmpTxt = $(this).val();
        $(this).val(tmpTxt.replace(/\D/g, ''));
    }).bind("paste", function () {
        var tmpTxt = $(this).val();
        $(this).val(tmpTxt.replace(/\D/g, ''));
    }).css("ime-mode", "disabled");
    var minDuration = "";
    $txtMinDuration.bind('input propertychange', function () {
        var curMinDuration = $(this).val().trim();
        if (curMinDuration === minDuration) {
            return;
        }
        minDuration = curMinDuration;
//            refreshJQGrid();
    });

    $txtMaxDuration.keyup(function () {
        var tmpTxt = $(this).val();
        $(this).val(tmpTxt.replace(/\D|^0/g, ''));
    }).bind("paste", function () {
        var tmpTxt = $(this).val();
        $(this).val(tmpTxt.replace(/\D|^0/g, ''));
    }).css("ime-mode", "disabled");
    var maxDuration = "";
    $txtMaxDuration.bind('input propertychange', function () {
        var curMaxDuration = $(this).val().trim();
        if (curMaxDuration === maxDuration) {
            return;
        }
        maxDuration = curMaxDuration;
//            refreshJQGrid();
    });
    //输入规则判断
    $(function () {
        $("#begin_date").val(getLastMonth());
        $("#end_date").val(getToday());
        $('#select_business').selectpicker();
        var createNotify = null;
        $.jgrid.defaults.responsive = true;
        $.jgrid.defaults.styleUI = "Bootstrap";
        var $artificialJQGrid = $("#artificialJQGrid").jqGrid({
            height: 434,
            autowidth: true,
            autoScroll: false,
            width: '100%',
            shrinkToFit: true, /*  autoScroll: false, *//*forceFit: true, */
            colNames: ["主键", "来电号码", "坐席分机", "呼入时间", "接听时间", "结束时间", "通话时长(mm:ss)"
                , "操作"],
            colModel: [
                {name: "id", index: "id", key: true, hidden: true},
                {name: "callerIdNumber", index: "callerIdNumber", width: "100%", autowidth: true, align: "left"},
                {name: "destinationNumber", index: "destinationNumber", width: "100%", autowidth: true, align: "left"},
                {name: "startStamp", index: "startStamp", align: "left", width: "100%",},
                {name: "answerStamp", index: "answerStamp", width: "100%", align: "left",},
                {name: "endStamp", index: "endStamp", width: "100%", align: "left",},
                {name: "billsec", index: "billsec", width: "100%", align: "left"},
                {name: "edit", index: "edit", align: "center", width: 200, autowidth: true,}
            ],
            pager: "#artificialJQGridPager",
            viewrecords: true,
            sortable: true,
            sortname: 'duration',
            hidegrid: false,
            multiselect: false,
            url: "<%=basePath%>/manualCall/list.do",
            postData: getJQGridFilterData(),
            datatype: 'json',
            rownumbers: true,
            rownumWidth: 100,
            rowNum: 30,
            rowList: [15, 30, 50],
            jsonReader: {
                root: "dataList", page: "currPage", total: "totalPages",          //   很重要 定义了 后台分页参数的名字。
                records: "totalCount", repeatitems: false, id: "id"
            },
            loadComplete: function (data) {
                // 自动调整高度
                var resCount = data.records;
                var tableHeight = resCount * 30 + 40;
                $("#gbox_artificialJQGrid .ui-jqgrid-bdiv").css(
                    "cssText",
                    "height: " + tableHeight + "px!important;");
            },
            gridComplete: function () {         // 数据加载完成后 添加 采购按钮
                $("#artificialJQGrid").jqGrid('setLabel', 'rn', '序号', {
                    'text-align': 'center',
                    'font-size': '12px',

                }, '');
                var ids = jQuery("#artificialJQGrid").jqGrid('getDataIDs');
                console.log(ids)
                for (var i = 0; i < ids.length; i++) {
                    var id = ids[i];
                    var rowData = jQuery("#artificialJQGrid").jqGrid('getRowData', id);
                    var statusHtml = "";
                    var download = "<button type='button' class='edit btn btn-link btn-xs'  onclick='exportOne(this, " + id + ")' style='margin-right: 2px'>下载</button>"
                    jQuery("#artificialJQGrid").jqGrid('setRowData', ids[i], {edit: download});


                }
            },
            beforeSelectRow: function (rowid, e) {

            },
            onSelectRow: function (rowid) {

            },
            ondblClickRow: function (id) {

            }

        });


        // 导出excel
        $("#export_excel").click(function () {
            var data = $("#artificialJQGrid").jqGrid('getRowData');
            if (data.length == 0) {
                myNotify("warning", "", "暂无数据可导出！");
            } else {
                window.location.href = "<%=basePath%>/manualCall/downLoadExcel.do?" +
                    "&startTime=" + getJQGridFilterData().startTime + "&endTime=" + getJQGridFilterData().endTime + "&callerIdNumber=" + getJQGridFilterData().callerIdNumber +
                    "&minBillsec=" + getJQGridFilterData().minBillsec + "&maxBillsec=" + getJQGridFilterData().maxBillsec
                    + "&destinationNumber=" + getJQGridFilterData().destinationNumber;
                ;
            }
        });

        // 导出语音
        $("#export_audio").click(function () {
            var data = $("#artificialJQGrid").jqGrid('getRowData');
            if (data.length == 0) {
                myNotify("warning", "", "暂无数据可导出！");
            } else {
                $.ajax(
                    {
                        url: "<%=basePath%>/manualCall/fileIsExit.do",
                        data: function () {
                            return"&startTime=" + getJQGridFilterData().startTime + "&endTime=" + getJQGridFilterData().endTime +
                                "&callerIdNumber=" + getJQGridFilterData().callerIdNumber +
                                "&minBillsec=" + getJQGridFilterData().minBillsec + "&maxBillsec=" + getJQGridFilterData().maxBillsec
                                + "&destinationNumber=" + getJQGridFilterData().destinationNumber;
                        }(),
                        async: false,
                        mtype: 'POST',
                        dataType: "json",
                        success:function (data){
                            if(data.errorCode==500){

                                return  myNotify("error", "", "访问资源不存在")
                            }
                            else {

                                location.href = "<%=basePath%>/manualCall/downLoadLuYinAll.do?" +
                                    "&startTime=" + getJQGridFilterData().startTime + "&endTime=" + getJQGridFilterData().endTime +
                                    "&callerIdNumber=" + getJQGridFilterData().callerIdNumber +
                                    "&minBillsec=" + getJQGridFilterData().minBillsec + "&maxBillsec=" + getJQGridFilterData().maxBillsec
                                    + "&destinationNumber=" + getJQGridFilterData().destinationNumber;


                            }
                            console.log(data)
                        },
                        error: function (msg) {
                            return  false
                            console.log(msg)

                        }
                    }
                )
            }
        });
        // 导出语音单条


        $(".closeDialog").click(function (e) {
            if (checkContentChange()) {
                bootbox.confirm({
                    size: "small",
                    message: "内容已修改，您还未保存，是否关闭该页面？",
                    buttons: {
                        confirm: {
                            label: "关闭"
                        },
                        cancel: {
                            label: "取消"
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            $("#modal_call_dialogue_info").modal('hide');
                        } else {

                        }
                    }
                })
            } else {
                $("#modal_call_dialogue_info").modal('hide');
            }
        });
        $('body').on('hidden.bs.modal', '.modal', function () {
            destroyWave();

        });

        $("#btnPlayPauseFullAudio").click(function () {
            waveSurfer.playPause();
        });

        /**
         * 保存人工校验结果
         */
        $("#form_manual_check1").submit(function (event) {
            var manualCheckResult = $("#select_manual_check_result").find("option:selected").val().trim();
            if (manualCheckResult == "0") {
                createNotify = myNotify("warning", "", "请正确选择人工校验结果！", createNotify);
                return false;
            }
            var manualCheckComment = $("#txt_manual_check_comment").val().trim();
            event.preventDefault();
            $.ajax({
                url: "<%=basePath%>/call/saveManualCheckResultInfo.do",
                data: function () {
                    return "callId=" + call_info.id + "&manualCheckResult=" + manualCheckResult + "&manualCheckComment=" + encodeURI(manualCheckComment);
                }(),
                async: false,
                dataType: "json",
                success: function (data) {
                    if (data["errorCode"] == "0") {
                        var manualResultHtml = getCallManualCheckResultContentByKey(manualCheckResult);
                        jQuery("#callInInfoJQGrid").jqGrid('setRowData', call_info.id, {manual_check_result: manualResultHtml});
                        createNotify = myNotify("success", "", "保存成功！", createNotify);
                        call_info.manualCheckResult = manualCheckResult;
                        call_info.manualCheckComment = manualCheckComment;
//                        $("#modal_call_dialogue_info").modal('hide');
                    } else {
                        createNotify = myNotify("error", "", "保存失败！", createNotify);
                    }
                },
                error: function () {
                }
            });


        });


        $("#btn_query").click(function () {
            refreshJQGrid();
        });
    });

    /******************************方法声明**********************************/
    /**
     * 刷新表格数据
     */
    function checkAudioOne(id){
        $.ajax(
            {
                url: "<%=basePath%>/manualCall/fileIsExit.do",
                data: function () {
                    return "id=" + id;
                }(),
                async: false,
                mtype: 'POST',
                dataType: "json",
                success:function (data){
                    if(data.error===500){
                        return false
                    }
                    else return  true
                    console.log(data)
                },
                error: function (msg) {
                    return  false
                    console.log(msg)

                }
            }
        )
    }


    function exportOne(obj, id) {
        $.ajax(
            {
                url: "<%=basePath%>/manualCall/fileIsExit.do",
                data: function () {
                    return "id=" + id;
                }(),
                async: false,
                mtype: 'POST',
                dataType: "json",
                success:function (data){
                    if(data.errorCode==500){
                        return  myNotify("error", "", "访问资源不存在")
                    }
                    else {
                        window.location.href ="<%=basePath%>/manualCall/downLoadLuYinOne.do?id=" + id;

                    }
                    console.log(data)
                },
                error: function (msg) {
                    return  false
                    console.log(msg)

                }
            }
        )


    }

    function refreshJQGrid() {
        $("#artificialJQGrid").jqGrid("setGridParam", {
            url: "<%=basePath%>/manualCall/list.do",
            mtype: 'POST',
            datatype: "json",
            postData: getJQGridFilterData(),
            page: 1
        }).trigger("reloadGrid");
    }

    // 获取筛选数据
    function getJQGridFilterData() {
        var postData = {};
        //坐席分机
        postData.destinationNumber = $("#destinationNumber").val().trim();
        //坐席号码
        postData.callerIdNumber = $("#txt_phone_number").val().trim();
        //最小通话时长
        postData.minBillsec = $("#txt_min_duration").val().trim();
        //最大通话时长
        postData.maxBillsec = $("#txt_max_duration").val().trim();
        //开始时间
        postData.startTime = $('#begin_date').val();
        //结束时间
        postData.endTime = $('#end_date').val();
        console.log(postData)
        return postData;
    }


    // 导出单个数据
    function exportSingleData(id) {
        window.location.href = "<%=basePath%>/manualCall/downLoadLuYinOne.do?id=" + id;
    }


    /**
     *
     * @returns {boolean} true： 内容有改 false：内容没改
     */







    function destroyWave() {
        $("#audio_progress").attr("aria-valuenow", 0);
        $("#audio_progress").css("width", '0%');
        $("#audio_progress").text('0%');
        $("#btnPlayPauseFullAudio").attr('disabled', true);
        waveSurfer.stop();
        waveSurfer.un('ready');
        waveSurfer.un('loading');
        $(this).removeData('bs.modal');
    }

    function beginDateClickRefreshTaskData() {
    }

</script>
</body>
</html>